#include <stdio.h>
#include <locale.h>
#include <strings.h>
#include <time.h>
#include <sys/epoll.h>
#include <stdlib.h>
#include <sys/types.h>	       /* See NOTES */
#include <sys/socket.h>
#include <fcntl.h>
#include <unistd.h>

#define MAX_EVENTS 500

typedef void (*call_back_t)(int fd, int events, void *argv);

struct myevent_s {
	int fd;
	call_back_t call_back;
	int events;
	void *arg;
	int status;
	char buf[128];
	int len;
	int s_offset;
	long last_active;
};

void set_event(struct myevent_s *ev, int fd, call_back_t call_back, void *arg)
{
	ev->fd = fd;
	ev->call_back = call_back;
	ev->events = 0;
	ev->arg = arg;
	ev->status = 0;
	bzero(ev->buf, sizeof(ev->buf));
	ev->s_offset = 0;
	ev->len = 0;
	ev->last_active = time(NULL);
}

void add_event(int epoll_fd, int events, struct myevent_s *ev)
{
	struct epoll_event epv = {0, {0}};
	int op;
	epv.data.ptr = ev;
	ev->events = events;
	epv.events = ev->events;

	if (1 == ev->status) {
		op = EPOLL_CTL_MOD;
	} else {
		op = EPOLL_CTL_ADD;
		ev->status = 1;
	}

	if (epoll_ctl(epoll_fd, op, ev->fd, &epv) < 0) {
		printf("%s:Event Add failed(fd=%d,event=%d)\n",__func__,ev->fd, events);
	} else {
		printf("%s:Event Add OK (fd=%d,op=%d,event=%0X)\n",__func__,ev->fd, op, events);
	}
}

void del_event(int epoll_fd, struct myevent_s *ev)
{
	struct epoll_event epv = {0,{0}};
	if (ev->status != 1) {
		return ;
	}

	epv.data.ptr = ev;
	ev->status = 0;
	epoll_ctl(epoll_fd, EPOLL_CTL_DEL, ev->fd, &epv);
}

int init_socket(int epoll_fd, short port)
{
	int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
	if (socket_fd < 0) {
		printf("%s:Create socket failed\n",__func__);
		goto INIT_SOCKET_FAILED;
	}

	fcntl(socket_fd, F_SETFL, O_NONBLOCK);	/*set non-blocking*/

	set_event()
	return 0;

INIT_SOCKET_FAILED:
	return -1;
}

int main(int argc, const char *argv[])
{
	int epoll_fd;
	unsigned short port = 12345; /* default port */
	if (argc == 2) {
		port = atoi(argv[1]);
	}
	setlocale(LC_ALL, "");
	
	/* carte epoll */
	epoll_fd = epoll_create(MAX_EVENTS);
	if (epoll_fd <= 0) {
		printf("%s:Create epoll failed %d\n",__func__, epoll_fd);
	}

	/* create & bind listen socket , and add to epoll, set non-blocking */
	init_socket(epoll_fd, port);


	return 0;
}
